import json

import requests
from typing import Optional, Dict, Any


class Api:
    def __init__(self, logger, base_url: str, headers: Optional[Dict[str, str]] = None, timeout: int = 10):
        """
        初始化API客户端
        :param base_url: 基础URL，所有请求将基于此URL
        :param headers: 默认请求头（可选）
        :param timeout: 默认超时时间（秒）
        """
        self.logger = logger
        self.base_url = base_url.rstrip('/')  # 确保没有结尾的斜杠
        self.headers = headers or {'Content-Type': 'application/json'}
        self.timeout = timeout

    def get(self, endpoint: str, params: Optional[Dict[str, Any]] = None,
            headers: Optional[Dict[str, str]] = None, timeout: Optional[int] = None) -> Dict[str, Any]:
        """
        GET请求
        :param endpoint: API端点（例如 "/users"）
        :param params: 请求参数（可选）
        :param headers: 自定义请求头（可选）
        :param timeout: 自定义超时时间（可选）
        :return: 包含响应内容或错误信息的字典
        """
        url = f"{self.base_url}/{endpoint.lstrip('/')}"
        merged_headers = {**self.headers, **(headers or {})}

        try:
            response = requests.get(
                url,
                params=params,
                headers=merged_headers,
                timeout=timeout or self.timeout
            )
            response.raise_for_status()  # 自动处理4xx/5xx错误
            return self._format_success_response(response)
        except requests.RequestException as e:
            return self._format_error_response(e)

    def post(self, endpoint: str, data: Optional[Dict[str, Any]] = None,
             json: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None,
             timeout: Optional[int] = None) -> Dict[str, Any]:
        """
        POST请求
        :param endpoint: API端点（例如 "/users"）
        :param data: 表单数据（可选）
        :param json: JSON数据（可选）
        :param headers: 自定义请求头（可选）
        :param timeout: 自定义超时时间（可选）
        :return: 包含响应内容或错误信息的字典
        """
        url = f"{self.base_url}/{endpoint.lstrip('/')}"
        merged_headers = {**self.headers, **(headers or {})}

        try:
            response = requests.post(
                url,
                data=data,
                json=json,
                headers=merged_headers,
                timeout=timeout or self.timeout
            )
            response.raise_for_status()
            return self._format_success_response(response)
        except requests.RequestException as e:
            return self._format_error_response(e)

    def _format_success_response(self, response: requests.Response) -> Dict[str, Any]:
        """统一格式化成功响应"""
        try:
            return {
                'success': True,
                'status_code': response.status_code,
                'data': response.json(),
                'headers': dict(response.headers)
            }
        except ValueError:  # 当响应不是JSON格式时
            return {
                'success': True,
                'status_code': response.status_code,
                'data': response.text,
                'headers': dict(response.headers)
            }

    def _format_error_response(self, exception: requests.RequestException) -> Dict[str, Any]:
        """统一格式化错误响应"""
        if isinstance(exception, requests.HTTPError):
            try:
                error_data = exception.response.json()
            except ValueError:
                error_data = exception.response.text
            return {
                'success': False,
                'status_code': exception.response.status_code,
                'error': str(exception),
                'response_data': error_data
            }
        else:
            return {
                'success': False,
                'status_code': None,
                'error': str(exception),
                'response_data': None
            }

    def sync_joints_data(self):
        """ 同步当前关节数据 """
        response = self.post("/queryJoints")
        self.logger.info(f"-----sync_joints_data:{response}")
        if response["success"]:
            return json.loads(response["data"]["data"])


    def load_and_play(self, data):
        """ 下发和测试动作 """
        self.logger.info(f"------load_and_play:{data}")
        response = self.post("/loadAndPlayMotion", json=data)
        self.logger.info(f"-----response:{response}")

    def upload_action_file(self, file):
        """ 上传动作文件 """
        pass

    def add_action(self):
        """ 新增动作 """
        pass



# 使用示例
if __name__ == "__main__":
    # 初始化客户端
    client = Api(
        base_url="https://jsonplaceholder.typicode.com",
        headers={'User-Agent': 'MyAPIClient/1.0'}
    )

    # 示例GET请求
    get_result = client.get("/todos/1")
    print("GET Result:", get_result)

    # 示例POST请求
    post_data = {
        "title": "foo",
        "body": "bar",
        "userId": 1
    }
    post_result = client.post("/posts", json=post_data)
    print("POST Result:", post_result)